<template>
  <div class="asset-inventory">
    <div class="header">
      <router-link to="/main/process" class="back-btn">
        <i class="el-icon-arrow-left"></i>
        <span>返回</span>
      </router-link>
      <h2>固定资产盘点作业流程</h2>
      <div class="header-actions">
        <el-button type="primary" icon="el-icon-menu" @click="showList">盘点列表</el-button>
      </div>
    </div>

    <div class="content">
      <el-form :model="formData" ref="form" :rules="rules" label-width="120px" class="inventory-form">
        <!-- 基本信息 -->
        <div class="form-section">
          <h3>基本信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="盘点编号" prop="inventoryNo">
                <el-input v-model="formData.inventoryNo" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="盘点日期" prop="inventoryDate">
                <el-date-picker
                  v-model="formData.inventoryDate"
                  type="date"
                  placeholder="选择盘点日期"
                  style="width: 100%">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="盘点部门" prop="department">
                <el-select v-model="formData.department" placeholder="请选择部门" style="width: 100%">
                  <el-option
                    v-for="dept in departments"
                    :key="dept.value"
                    :label="dept.label"
                    :value="dept.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="盘点人" prop="operator">
                <el-input v-model="formData.operator"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 盘点范围 -->
        <div class="form-section">
          <h3>盘点范围</h3>
          <el-form-item label="资产类别" prop="assetTypes">
            <el-checkbox-group v-model="formData.assetTypes">
              <el-checkbox label="computer">电脑设备</el-checkbox>
              <el-checkbox label="office">办公设备</el-checkbox>
              <el-checkbox label="furniture">办公家具</el-checkbox>
              <el-checkbox label="vehicle">车辆</el-checkbox>
              <el-checkbox label="other">其他设备</el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item label="盘点区域" prop="areas">
            <el-input type="textarea" v-model="formData.areas" rows="3" placeholder="请输入需要盘点的具体区域"></el-input>
          </el-form-item>
        </div>

        <!-- 盘点明细 -->
        <div class="form-section">
          <h3>盘点明细</h3>
          <el-table
            :data="formData.inventoryItems"
            border
            style="width: 100%">
            <el-table-column prop="assetNo" label="资产编号" width="150"></el-table-column>
            <el-table-column prop="assetName" label="资产名称" width="180"></el-table-column>
            <el-table-column prop="specification" label="规格型号"></el-table-column>
            <el-table-column prop="location" label="存放地点" width="150"></el-table-column>
            <el-table-column prop="status" label="状态" width="120">
              <template slot-scope="scope">
                <el-select v-model="scope.row.status" placeholder="请选择">
                  <el-option label="正常" value="normal"></el-option>
                  <el-option label="待维修" value="repair"></el-option>
                  <el-option label="闲置" value="idle"></el-option>
                  <el-option label="报废" value="scrap"></el-option>
                  <el-option label="丢失" value="lost"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="danger"
                  @click="removeInventoryItem(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 10px;">
            <el-button type="primary" size="small" @click="addInventoryItem">添加资产</el-button>
          </div>
        </div>

        <!-- 盘点结果 -->
        <div class="form-section">
          <h3>盘点结果</h3>
          <el-form-item label="盘点结论" prop="conclusion">
            <el-input
              type="textarea"
              v-model="formData.conclusion"
              :rows="4"
              placeholder="请总结盘点情况，包括资产状况、存在问题等">
            </el-input>
          </el-form-item>

          <el-form-item label="处理建议" prop="suggestions">
            <el-input
              type="textarea"
              v-model="formData.suggestions"
              :rows="4"
              placeholder="请提出相关处理建议">
            </el-input>
          </el-form-item>
        </div>

        <!-- 附件信息 -->
        <div class="form-section">
          <h3>附件信息</h3>
          <el-form-item label="相关附件" prop="attachments">
            <el-upload
              action="/api/file/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              multiple
              :limit="5"
              :file-list="formData.attachments">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                可上传盘点照片、清单等相关文件，单个文件不超过10MB
              </div>
            </el-upload>
          </el-form-item>
        </div>

        <!-- 步骤操作按钮 -->
        <div class="step-actions">
          <el-button 
            v-if="currentStep > 0" 
            @click="prevStep">
            <i class="el-icon-arrow-left"></i> 上一步
          </el-button>
          <el-button 
            type="primary" 
            @click="nextStep"
            v-if="currentStep < processSteps.length - 1">
            下一步 <i class="el-icon-arrow-right"></i>
          </el-button>
          <el-button 
            type="success" 
            @click="finishProcess"
            v-else>
            完成 <i class="el-icon-check"></i>
          </el-button>
        </div>
      </el-form>
    </div>

    <!-- 添加资产对话框 -->
    <el-dialog title="添加资产" :visible.sync="assetDialogVisible" width="50%">
      <el-form :model="assetForm" ref="assetForm" :rules="assetRules" label-width="100px">
        <el-form-item label="资产编号" prop="assetNo">
          <el-input v-model="assetForm.assetNo"></el-input>
        </el-form-item>
        <el-form-item label="资产名称" prop="assetName">
          <el-input v-model="assetForm.assetName"></el-input>
        </el-form-item>
        <el-form-item label="规格型号" prop="specification">
          <el-input v-model="assetForm.specification"></el-input>
        </el-form-item>
        <el-form-item label="存放地点" prop="location">
          <el-input v-model="assetForm.location"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="assetForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="正常" value="normal"></el-option>
            <el-option label="待维修" value="repair"></el-option>
            <el-option label="闲置" value="idle"></el-option>
            <el-option label="报废" value="scrap"></el-option>
            <el-option label="丢失" value="lost"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="assetDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddAsset">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 盘点列表对话框 -->
    <el-dialog title="盘点记录列表" :visible.sync="listDialogVisible" width="80%">
      <div class="filter-section">
        <el-input
          v-model="searchQuery"
          placeholder="请输入盘点编号/部门"
          style="width: 200px"
          clearable
          @input="handleSearch">
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        
        <el-select v-model="statusFilter" placeholder="盘点状态" clearable @change="handleSearch">
          <el-option label="进行中" value="processing"></el-option>
          <el-option label="已完成" value="completed"></el-option>
          <el-option label="已取消" value="cancelled"></el-option>
        </el-select>
        
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleSearch">
        </el-date-picker>
      </div>
      
      <el-table :data="filteredList" border style="width: 100%">
        <el-table-column prop="inventoryNo" label="盘点编号" width="180"></el-table-column>
        <el-table-column prop="department" label="盘点部门" width="150"></el-table-column>
        <el-table-column prop="operator" label="盘点人" width="120"></el-table-column>
        <el-table-column prop="inventoryDate" label="盘点日期" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.inventoryDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" @click="viewDetail(scope.row)">查看</el-button>
            <el-button 
              size="mini" 
              type="primary" 
              v-if="scope.row.status === 'processing'"
              @click="editInventory(scope.row)">
              编辑
            </el-button>
            <el-button 
              size="mini" 
              type="danger"
              v-if="scope.row.status === 'processing'"
              @click="cancelInventory(scope.row)">
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'AssetInventoryProcess',
  data() {
    return {
      formData: {
        inventoryNo: this.generateInventoryNo(),
        inventoryDate: new Date(),
        department: '',
        operator: '',
        assetTypes: [],
        areas: '',
        inventoryItems: [],
        conclusion: '',
        suggestions: '',
        attachments: []
      },
      departments: [
        { value: 'tech', label: '技术部' },
        { value: 'hr', label: '人力资源部' },
        { value: 'finance', label: '财务部' },
        { value: 'admin', label: '行政部' }
      ],
      rules: {
        department: [{ required: true, message: '请选择盘点部门', trigger: 'change' }],
        operator: [{ required: true, message: '请输入盘点人', trigger: 'blur' }],
        assetTypes: [{ type: 'array', required: true, message: '请选择资产类别', trigger: 'change' }],
        areas: [{ required: true, message: '请输入盘点区域', trigger: 'blur' }],
        conclusion: [{ required: true, message: '请填写盘点结论', trigger: 'blur' }]
      },
      assetDialogVisible: false,
      assetForm: {
        assetNo: '',
        assetName: '',
        specification: '',
        location: '',
        status: 'normal'
      },
      assetRules: {
        assetNo: [{ required: true, message: '请输入资产编号', trigger: 'blur' }],
        assetName: [{ required: true, message: '请输入资产名称', trigger: 'blur' }],
        location: [{ required: true, message: '请输入存放地点', trigger: 'blur' }]
      },
      currentStep: 0,
      processSteps: [
        {
          title: '基本信息',
          description: '填写盘点基本信息',
          icon: 'el-icon-document'
        },
        {
          title: '盘点范围',
          description: '确定盘点范围和要求',
          icon: 'el-icon-aim'
        },
        {
          title: '人员安排',
          description: '分配盘点人员',
          icon: 'el-icon-user'
        },
        {
          title: '时间计划',
          description: '制定盘点时间计划',
          icon: 'el-icon-date'
        }
      ],
      listDialogVisible: false,
      searchQuery: '',
      statusFilter: '',
      dateRange: null,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      filteredList: []
    }
  },
  methods: {
    generateInventoryNo() {
      const date = new Date()
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
      return `PD${year}${month}${day}${random}`
    },
    addInventoryItem() {
      this.assetForm = {
        assetNo: '',
        assetName: '',
        specification: '',
        location: '',
        status: 'normal'
      }
      this.assetDialogVisible = true
    },
    confirmAddAsset() {
      this.$refs.assetForm.validate(valid => {
        if (valid) {
          this.formData.inventoryItems.push({...this.assetForm})
          this.assetDialogVisible = false
        }
      })
    },
    removeInventoryItem(index) {
      this.formData.inventoryItems.splice(index, 1)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleRemove(file, fileList) {
      this.formData.attachments = fileList
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    async submitForm() {
      try {
        await this.$refs.form.validate()
        // TODO: 发送请求到后端
        this.$message.success('申请提交成功')
        this.$router.push('/main/process')
      } catch (error) {
        this.$message.error(error.message || '请填写完整的申请信息')
      }
    },
    resetForm() {
      this.$refs.form.resetFields()
      this.formData.inventoryNo = this.generateInventoryNo()
      this.formData.inventoryDate = new Date()
      this.formData.inventoryItems = []
      this.formData.attachments = []
    },
    nextStep() {
      if (this.currentStep < this.processSteps.length - 1) {
        this.$refs.form.validateField(this.getCurrentStepFields(), valid => {
          if (!valid) {
            this.currentStep++
            this.scrollToTop()
          }
        })
      }
    },
    prevStep() {
      if (this.currentStep > 0) {
        this.currentStep--
        this.scrollToTop()
      }
    },
    getCurrentStepFields() {
      // 根据当前步骤返回需要验证的字段
      const fieldMap = {
        0: ['inventoryNo', 'inventoryDate', 'department', 'operator'],
        1: ['assetTypes', 'areas'],
        2: ['inventoryTeam', 'supervisor'],
        3: ['startDate', 'endDate', 'schedule']
      }
      return fieldMap[this.currentStep] || []
    },
    scrollToTop() {
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      })
    },
    finishProcess() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$confirm('确认完成盘点计划制定？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'success'
          }).then(() => {
            // TODO: 提交表单数据
            this.$message.success('盘点计划已创建')
            this.$router.push('/main/process')
          }).catch(() => {})
        }
      })
    },
    showList() {
      this.listDialogVisible = true
      this.loadInventoryList()
    },
    async loadInventoryList() {
      try {
        // TODO: 调用API获取列表数据
        this.filteredList = [
          {
            inventoryNo: 'PD202403010001',
            department: '技术部',
            operator: '张三',
            inventoryDate: '2024-03-01',
            status: 'processing'
          },
          // ... 更多测试数据
        ]
        this.total = this.filteredList.length
      } catch (error) {
        this.$message.error('加载列表失败')
      }
    },
    handleSearch() {
      // 实现搜索逻辑
      let results = [...this.filteredList]
      
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        results = results.filter(item => 
          item.inventoryNo.toLowerCase().includes(query) ||
          item.department.toLowerCase().includes(query)
        )
      }
      
      if (this.statusFilter) {
        results = results.filter(item => item.status === this.statusFilter)
      }
      
      if (this.dateRange) {
        // 实现日期筛选逻辑
      }
      
      this.total = results.length
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      this.filteredList = results.slice(start, end)
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.handleSearch()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.handleSearch()
    },
    getStatusType(status) {
      const typeMap = {
        processing: 'warning',
        completed: 'success',
        cancelled: 'info'
      }
      return typeMap[status] || ''
    },
    getStatusText(status) {
      const textMap = {
        processing: '进行中',
        completed: '已完成',
        cancelled: '已取消'
      }
      return textMap[status] || status
    },
    formatDate(date) {
      return new Date(date).toLocaleDateString()
    },
    viewDetail(row) {
      // TODO: 实现查看详情功能
      console.log('查看详情:', row)
    },
    editInventory(row) {
      // TODO: 实现编辑功能
      console.log('编辑盘点:', row)
    },
    cancelInventory(row) {
      this.$confirm('确认取消该盘点任务？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // TODO: 调用取消API
        this.$message.success('已取消')
        this.loadInventoryList()
      }).catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.asset-inventory {
  padding: 20px;

  .header {
    margin-bottom: 30px;
    position: relative;
    text-align: center;

    .back-btn {
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      text-decoration: none;
      color: #606266;
      display: flex;
      align-items: center;
    }

    h2 {
      margin: 0;
      font-size: 24px;
      color: #303133;
    }

    .header-actions {
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
    }
  }

  .content {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);

    .inventory-form {
      max-width: 1000px;
      margin: 0 auto;

      .step-actions {
        margin-top: 30px;
        padding-top: 20px;
        border-top: 1px solid #EBEEF5;
        text-align: center;
        
        .el-button {
          margin: 0 10px;
          padding: 12px 25px;
          
          i {
            margin: 0 5px;
          }
        }
      }
    }
  }

  .form-section {
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid #EBEEF5;

    &:last-child {
      border-bottom: none;
    }

    h3 {
      margin: 0 0 20px;
      padding-left: 10px;
      border-left: 4px solid #409EFF;
      font-size: 18px;
      font-weight: 500;
      color: #303133;
    }
  }

  .form-actions {
    text-align: center;
    margin-top: 40px;
  }

  .el-upload__tip {
    color: #909399;
  }

  .filter-section {
    margin-bottom: 20px;
    display: flex;
    gap: 15px;
    align-items: center;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 